package cn.jinjimi.app.main.fragment;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import bolts.Continuation;
import bolts.Task;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.Constants;
import cn.jinjimi.app.controller.AccountController;
import cn.jinjimi.app.controller.UserController;
import cn.jinjimi.app.main.activity.LoginActivity;
import cn.jinjimi.app.main.extend.BaseFragment;
import cn.jinjimi.app.main.widget.MTextWatcher;
import cn.jinjimi.app.main.widget.PhoneBaseEditTextView;
import cn.jinjimi.app.util.ToastUtil;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.domain.data.dto.BaseResDto;

/**
 *
 * @author zhenhua
 */
public class ResetPswFragment extends BaseFragment implements View.OnClickListener {
    private PhoneBaseEditTextView phone;
    private Button cleanPhone;
    private EditText valid;
    private Button cleanValid;
    private TextView getValid;
    private EditText psw;
    private Button cleanPsw;
    private EditText psw1;
    private Button cleanPsw1;
    private TextView submit;

    public static ResetPswFragment newInstance(String text) {
        ResetPswFragment fragment = new ResetPswFragment();
        Bundle args = new Bundle();
        args.putString("operationToken", text);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutResourceId() {
        return R.layout.fragment_reset_psw;
    }

    @Override
    protected void initial() {
        initView();
        initListener();
    }

    protected void initView() {
        getActivity().setTitle(R.string.title_retrieve_psw);
        //手机号
        phone = (PhoneBaseEditTextView) findView().findViewById(R.id.et_phone);
        phone.setHint(getString(R.string.prompt_find_psw_mobile));
        //清除手机号码
        cleanPhone = (Button) findView().findViewById(R.id.bt_clean_phone_number);
        //验证码
        valid = (EditText) findView().findViewById(R.id.valid_code);
        //清除验证码
        cleanValid = (Button) findView().findViewById(R.id.clean_valid_code);
        //获取验证码
        getValid = findView().findViewById(R.id.get_valid_code);
        psw = (EditText) findView().findViewById(R.id.et_password);
        cleanPsw = (Button) findView().findViewById(R.id.bt_clean_password);
        psw1 = (EditText) findView().findViewById(R.id.et_password_again);
        cleanPsw1 = (Button) findView().findViewById(R.id.bt_clean_password_again);
        submit =  findView().findViewById(R.id.bt_submit);
        cleanPhone.setVisibility(StringUtils.isEmpty(phone.getText().toString()) ? View.GONE : View.VISIBLE);
    }

    protected void initListener() {
        cleanPsw.setOnClickListener(this);
        cleanPsw1.setOnClickListener(this);
        submit.setOnClickListener(this);
        psw.addTextChangedListener(new MTextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    cleanPsw.setVisibility(View.INVISIBLE);
                } else {
                    cleanPsw.setVisibility(View.VISIBLE);
                }
            }
        });
        psw1.addTextChangedListener(new MTextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    cleanPsw1.setVisibility(View.INVISIBLE);
                } else {
                    cleanPsw1.setVisibility(View.VISIBLE);
                }
            }
        });

        cleanPhone.setOnClickListener(this);
        cleanValid.setOnClickListener(this);
        getValid.setOnClickListener(this);

        phone.addTextChangedListener(new MTextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 手机号框变化时判断框内是否为空，是就设置clean显示
                if (!TextUtils.isEmpty(s)) {
                    cleanPhone.setVisibility(View.VISIBLE);
                } else {
                    cleanPhone.setVisibility(View.INVISIBLE);
                }
            }
        });
        valid.addTextChangedListener(new MTextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 验证码框变化时判断框内是否为空，是就设置clean显示
                if (!TextUtils.isEmpty(s)) {
                    cleanValid.setVisibility(View.VISIBLE);
                } else {
                    cleanValid.setVisibility(View.INVISIBLE);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_clean_password:
                psw.setText("");
                break;
            case R.id.bt_clean_password_again:
                psw1.setText("");
                break;
            case R.id.get_valid_code:
                if (StringUtils.checkPhoneNum(getActivity(), phone)) {
                    getVerifyCaptcha(phone.getRealPhoneNum());
                }
                break;
            case R.id.bt_clean_phone_number:
                phone.setText("");
                break;
            case R.id.clean_valid_code:
                valid.setText("");
                break;
            case R.id.bt_submit:
                if (StringUtils.checkPhoneNum(getActivity(), phone)) {
                    if (StringUtils.checkValidCode(getActivity(), valid)) {
                        submit();
                    }
                }
                break;
            default:break;
        }
    }

    /**
     * 获取验证码
     *
     */
    private void getVerifyCaptcha(String mobile) {
        valid.requestFocus();
        AccountController
                .getCaptcha(mobile)
                .onSuccess(new Continuation<Boolean, Void>() {
                    @Override
                    public Void then(Task<Boolean> task) throws Exception {
                        if (task.getResult()) {
                            ToastUtil.showCusToast(getActivity(), getResources().getString(R.string.account_send_captcha));
                        }
                        return null;
                    }
                }, Task.UI_THREAD_EXECUTOR);
    }

    private boolean checkPasswordInput(String pwd) {
        if (StringUtils.isEmpty(pwd)) {
            ToastUtils.toastMessage(getActivity(), R.string.input_u_password);
            return false;
        }
        return true;
    }

    private boolean checkPhoneInput(String mobile) {
        if (TextUtils.isEmpty(mobile)) {
            ToastUtils.toastMessage(getActivity(), cn.jinjimi.base.R.string.empty_phone);
            return false;
        }
        if (!StringUtils.isMobile(mobile)) {
            ToastUtils.toastMessage(getActivity(), cn.jinjimi.base.R.string.input_u_correct_phone);
        }
        return true;
    }

    /**
     * 提交请求
     */
    private void submit() {
        String pwdStr = psw.getText().toString();
        String pwdStr1 = psw1.getText().toString();
        if (!TextUtils.equals(pwdStr, pwdStr1)) {
            ToastUtils.toastMessage(getActivity(), R.string.psw_not_same);
            return;
        }

        if (!checkPasswordInput(pwdStr)) {
            return;
        }

        final String mobile = phone.getRealPhoneNum();
        if (!checkPhoneInput(mobile)) {
            return;
        }

        final String captcha = valid.getText().toString();
        if (!checkCaptchaInput(captcha)) {
            return;
        }

        ((LoginActivity) getActivity()).showLoadingIndicator();
        UserController
                .resetPassword(mobile, pwdStr, captcha)
                .onSuccess(new Continuation<BaseResDto, Void>() {
                    @Override
                    public Void then(Task<BaseResDto> task) throws Exception {
                        ((LoginActivity) getActivity()).hideLoadingIndicator();
                        if (task.isCompleted()) {
                            BaseResDto dto = task.getResult();
                            if (dto.result) {
                                ToastUtils.toastMessage(getActivity(), R.string.account_reset_password_success);
                                getActivity().finish();
                            } else if (dto.code == Constants.Code.CODE_USER_NOT_FOUND) {
                                onFirstLogin(mobile, captcha);
                            }
                        }
                        return null;
                    }
                }, Task.UI_THREAD_EXECUTOR);
    }

    private void onFirstLogin(String mobile, String captcha) {
        FragmentManager fm = getActivity().getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.content_fragment,
                RegisterPswFragment.newInstance(mobile, captcha),
                null);
        ft.addToBackStack(null);
        ft.commit();
    }

    private boolean checkCaptchaInput(String captcha) {
        if (TextUtils.isEmpty(captcha)) {
            ToastUtils.toastMessage(getActivity(), R.string.account_check_captcha);
            return false;
        }
        return true;
    }

}
